package com.patzn.osgi.tracker.http.core;

import com.patzn.osgi.tracker.http.api.RequestHandler;
import org.osgi.framework.BundleContext;
import org.osgi.framework.ServiceReference;
import org.osgi.util.tracker.ServiceTrackerCustomizer;

public class HttpCoreTrackerCustomizer implements ServiceTrackerCustomizer<RequestHandler, RequestHandler> {

    private HttpServer httpServer;
    private BundleContext bundleContext;

    public HttpCoreTrackerCustomizer(HttpServer httpServer, BundleContext bundleContext) {
        this.httpServer = httpServer;
        this.bundleContext = bundleContext;
    }

    @Override
    public RequestHandler addingService(ServiceReference<RequestHandler> serviceReference) {
        String httpUrl = String.valueOf(serviceReference.getProperty("http.url"));
        if (httpUrl != null) {
            RequestHandler requestHandler = bundleContext.getService(serviceReference);
            if (httpServer.exists(httpUrl)) {
                System.out.println("exists");
            } else {
                httpServer.addHandler(httpUrl, requestHandler);
                return requestHandler;
            }
        }
        return null;
    }

    @Override
    public void modifiedService(ServiceReference<RequestHandler> serviceReference, RequestHandler requestHandler) {

    }

    @Override
    public void removedService(ServiceReference<RequestHandler> serviceReference, RequestHandler requestHandler) {
        String httpUrl = String.valueOf(serviceReference.getProperty("http.url"));
        if (httpUrl != null) {
            httpServer.removeHandler(httpUrl);
        }
    }
}
